package jp.tkym.labs.util.date;

import java.util.Calendar;
import java.util.Date;

class DateResolver{
	private Calendar cal = Calendar.getInstance();
	private static final long ONE_DAY = 24 * 60 * 60 * 1000;   
	
	private synchronized DateBean toBean(Date date){
		DateBean bean = new DateBean();
		cal.setTime(date);
		bean.year = cal.get(Calendar.YEAR);
		bean.month = cal.get(Calendar.MONTH) + 1;
		bean.day = cal.get(Calendar.DAY_OF_MONTH);
		bean.hour = cal.get(Calendar.HOUR);
		bean.minute = cal.get(Calendar.MINUTE);
		bean.second = cal.get(Calendar.SECOND);
		return bean;
	}
	
	private synchronized Date toDate(DateBean bean){
		cal.set(Calendar.YEAR, bean.year);
		cal.set(Calendar.MONTH, bean.month - 1);
		cal.set(Calendar.DAY_OF_MONTH, bean.day);
		cal.set(Calendar.HOUR, bean.hour);
		cal.set(Calendar.MINUTE, bean.minute);
		cal.set(Calendar.SECOND, bean.second);
		return cal.getTime();
	}
	
	Date toDate(int yyyymmdd){
		int day = yyyymmdd % 100;
		int yyyymm = (yyyymmdd-day) / 100;
		int month = yyyymm % 100;
		int year = yyyymm / 100;
		return toDate(year, month, day);
	}
	
	int toYyyymmdd(Date date){
		DateBean bean = toBean(date);
		return bean.year * 10000 + bean.month * 100 + bean.day;
	}
	
	private Date toDate(int year, int month, int day){
		return toDate(year, month, day, 0, 0, 0);
	}
	
	private Date toDate(int year, int month, int day, int hour, int minute, int second){
		DateBean bean = new DateBean();
		bean.year = year;
		bean.month = month;
		bean.day = day;
		bean.hour = hour;
		bean.minute = minute;
		bean.second = second;
		return toDate(bean);
	}
	
	Date tomorrow(Date date){
		return addDay(date, 1);
	}
	
	Date yesterday(Date date){
		return addDay(date, -1);
	}

	synchronized Date addMonth(Date today, int amount){
		cal.setTime(today);
		cal.add(Calendar.MONTH, amount);
		return cal.getTime();
	}
	
	synchronized Date addDay(Date today, int amount){
		cal.setTime(today);
		cal.add(Calendar.DATE, amount);
		return cal.getTime();
	}
	
	Date after(Date a, Date b){
		if(a.after(b)) return a;
		if(a.before(b)) return b;
		return a;
	}

	Date before(Date a, Date b){
		if(a.after(b)) return b;
		if(a.before(b)) return a;
		return a;
	}
	
	int days(Date start, Date end){
		if(start.after(end)) throw new IllegalArgumentException();
		long sL = start.getTime();
		long eL = end.getTime();
		double d = (eL - sL) / ONE_DAY ;
		return (int) Math.round(d);
	}
	
	class DateBean{
		int year;
		int month;
		int day;
		int hour;
		int minute;
		int second;
	}
}